package com.bjtu.ptsite.controller;

import com.bjtu.ptsite.exception.InsufficientPointsException;
import com.bjtu.ptsite.exception.SeedNotFoundException;
import com.bjtu.ptsite.exception.TorrentCreationException;
import com.bjtu.ptsite.exception.UserNotFoundException;
import com.bjtu.ptsite.model.*;
import com.bjtu.ptsite.service.*;
import com.bjtu.ptsite.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 *
 * SeedController.java (种子管理模块接口层)
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/seeds")
public class SeedController {
    private final SeedingService seedingService;
    private final PointsService pointsService;
    private final UserService userService;
    private static final String ROLE_ADMINISTRATOR = "admin";

    public SeedController(SeedingService seedingService, PointsService pointsService,UserService userService) {
        this.seedingService = seedingService;
        this.pointsService = pointsService;
        this.userService = userService;
    }

    /**
     *
     * 做种状态上报接口
     *
     * @author Zehao Wang, Junjie Zhang, Yutao Wei
     *
     */
    @Deprecated
    @PostMapping("/{seedId}/report-seeding")
    public ResponseEntity<?> reportSeeding(
            @PathVariable Long seedId,
            @RequestParam("userId") int userId) {

        seedingService.updateSeedingStatus(seedId, userId);
        return ResponseEntity.ok(Map.of("message", "做种状态已更新"));
    }

    /**
     *
     * 积分兑换接口
     *
     * @author Zehao Wang, Junjie Zhang, Yutao Wei
     *
     */
    @PostMapping("/points/exchange")
    public ResponseEntity<?> exchangePoints(
            @RequestBody PointsExchangeRequest request) {
        try {
            Integer userId = RequestUtil.getUserContext().getId();
            if(userId!=request.userId()){
                return ResponseEntity.badRequest().body(Map.of("error","你不能兑换其他人的积分"));
            }
            pointsService.exchangePoints(request.userId(), request.points());
            return ResponseEntity.ok(Map.of("message", "积分兑换成功"));
        } catch (InsufficientPointsException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", "用户不存在"));
        }
    }

    @PostMapping("/points/receive")
    public ResponseEntity<?> receivePoints(
            @RequestBody PointsExchangeRequest request) {
        int curUserId = RequestUtil.getUserContext().getId();
        User curUser = userService.getUserById(curUserId);
        if(!Objects.equals(curUser.getRole(), ROLE_ADMINISTRATOR)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(Map.of("error", "你不是管理员，不过我更好奇你是怎么发送这个请求的"));
        }
        try {
            log.info("用户 {} 获取积分: {}", request.userId(), request.points());
            pointsService.receivePoints(request.userId(), request.points());
            return ResponseEntity.ok(Map.of("message", "积分变更成功"));
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("error", "用户不存在"));
        }
    }

    @PostMapping("/comment")
    public Result comment(@RequestBody TorrentCommentRequest torrentCommentRequest){
        if(torrentCommentRequest==null){
            return  Result.error("传参不允许为空");
        }
        Long torrentId = torrentCommentRequest.getTorrentId();
        Long userId = torrentCommentRequest.getUserId();
        if(!userId.equals(Long.valueOf(RequestUtil.getUserContext().getId()))){
            return Result.error("请不要冒充他人评论");
        };
        if(torrentId==null){
            return Result.error("种子id不能为空");
        }
        seedingService.comment(torrentCommentRequest);
        return Result.success();
    }

    @PostMapping("/likes")
    public Result likes(@RequestBody TorrentCommentRequest torrentCommentRequest){
        if(torrentCommentRequest==null){
            return  Result.error("传参不允许为空");
        }
        Long id = torrentCommentRequest.getId();
        if(seedingService.selectById(id)==null){
            return Result.error("该评论不存在");
        }
        Long userId= (long)RequestUtil.getUserContext().getId();
        if(seedingService.likeExist(userId,id)==true){
            return Result.error("你已点过赞");
        }
        torrentCommentRequest.setUserId(userId);
        if(id==null){
            return Result.error("id不能为空");
        }
        seedingService.likes(torrentCommentRequest);
        return Result.success();
    }

    @PostMapping("/deleteComment")
    public Result deleteComment(@RequestBody TorrentCommentRequest torrentCommentRequest){
        if(torrentCommentRequest==null){
            return  Result.error("传参不允许为空");
        }
        Long id = torrentCommentRequest.getId();
        int userId = RequestUtil.getUserContext().getId();
        User curUser = userService.getUserById(userId);
        if(id==null){
            return Result.error("id不能为空");
        }
        if(!seedingService.selectById(id).getUserId().equals(Long.valueOf(userId)) && !curUser.getRole().equals(ROLE_ADMINISTRATOR)){
            return Result.error("你无法删除他人的评论");
        }
        seedingService.deleteComment(torrentCommentRequest);
        return Result.success();
    }

    @GetMapping("/getCommentList")
    public Result getCommentList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long torrentId
    ) {
        TorrentCommentRequest req = new TorrentCommentRequest();
        req.setPage(page);
        req.setSize(size);
        req.setTorrentId(torrentId);
        return Result.success(seedingService.getCommentList(req));
    }
}
